/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
  
    $("#observacao").keydown(function(event){
    if($(this).val().length >= 100) {
      event.preventDefault();
      return false;
    }
  });
});

$(function() {
    
    $("select").keypress(selectAsYouType(this)).blur(clearKeysPressed(this));
    
    $("input").keypress(preventEnterSubmit(this));
    
    $(".quant, #precoprod").each(function(){
        $(this).change(function(){
            //   alert($(this).val()); 
            $(this).val($(this).val() == "" ? "" + 0 : $(this).val());
            var total = 0;
                      
            $(".quant").each(function(){
                         
                if($(this).val() != "")
                {
                    // alert("entrou");
                    value = parseFloat($(this).val() == "" ? 0 : $(this).val().replace(/,/,"."));
                    total += value * parseFloat($("#precoprod").val() == "" ? 0 : $("#precoprod").val().replace(/,/,"."));
                }                       
                     
            })
            $("#precototal").val((""+total.toFixed(2)).replace(/\./,","));
        })
    }); 
                                 
    $( ".date" ).datepicker();
    $(".date").mask("99/99/9999");
    $(".cnpj").mask("99.999.999/9999-99");
    $(".percent").mask("999");
    $(".money").keypress(function(e){
        if (e.which != 44 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
 
    });
    $(".number").keypress(function(e){
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
 
    });
                
    $(".mainMenu").button();
    $(".edit").button({
        icons: {
            primary: "ui-icon-pencil"
        }
    });
     $(".print").button({
        icons: {
            primary: "ui-icon-print"
        }
    });
    $(".export").button({
        icons: {
            primary: "ui-icon-arrowthick-1-s"
        }
    });
    $(".detail").button({
        icons: {
            primary: "ui-icon-document"
        }
    });
    $(".delete").button({
        icons: {
            primary: "ui-icon-closethick"
        }
    });
    $(".add").button({
        icons: {
            primary: "ui-icon-plusthick"
        }
    });
    $(".search").button({
        icons: {
            primary: "ui-icon-search"
        }
    });
    $(".save").button({
        icons: {
            primary: "ui-icon-disk"
        }
    });
                
    $("#referencia").bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "autocomplete" ).menu.active ) {
            event.preventDefault();
        }
    }).autocomplete({
        source : function(request, response) {
            $.ajax({
                url : 'sjauto',
                dataType : 'json',
                data : {
                    name : request.term
                },
                success : function(data) {
                           
                    response($.map(data, function(item) {
                        return {
                            label: item.referencia,
                            value: item.referencia,
                            id: item.id,
                            preco: item.preco
                        }
                    }))
                }
            })
        },
        select: function(event,ui)
        {
            $("#precoprod").val((""+ui.item.preco.toFixed(2)).replace(/\./,","));
            $("#precoprod").change();
            $("#pid").val(""+ui.item.id);
            $(".quant").each(function(){
                $(this).val($(this).val() == "" ? "" + 0 : $(this).val().replace(/\./,","));
            });
        }
    });
                
                
});

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
                if (this === e.target) {
                    focusNext = true;
                }
                else if (focusNext){
                    $(this).focus();
                    return false;
                }
            });

            return false;
        }
    }
}
        
        
function confimDelete(model)
{
            
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: true,
        buttons: {
            "Sim": function() {
                $.ajax({
                    url: "delete?id="+model,
                    success: removeRow(this,model)                                     
                                          
                })
            },
            "Não": function() {
                $( this ).dialog( "close" );
            }
        }
    });
}

function removeRow(dialog,model)
{
    $( dialog ).dialog( "close" );
    $("#line"+model).remove();  
}

function excluiItem(id)
{
    $.ajax({
        url : 'excluiItem',
        data : {
            id : id
        },
        success: function(data)
        {
            $("#line"+id).remove(); 
                 $.ajax({
                            url : 'totalPedido',
                            data : {                              
                            },
                            success: function(data)
                            {
                                $("#displayValorTotal").text(data.toFixed(2)+"");
                            }
                    });
        }
    });

}

function addItem()
{
   
    $.ajax({
        url : 'addItem',
        dataType : 'json',
        data : {
            idProduto : $("#pid").val(),
            quantidade2: $("#quant2").val(),
            quantidade4: $("#quant4").val(),
            quantidade8: $("#quant8").val(),
            quantidade10: $("#quant10").val(),
            quantidade12: $("#quant12").val(),
            quantidade14: $("#quant14").val(),
            quantidade16: $("#quant16").val(),
            quantidade18: $("#quant18").val(),
            quantidadeP: $("#quantP").val(),
            quantidadeM: $("#quantM").val(),
            quantidadeG: $("#quantG").val(),
            quantidadeGG: $("#quantGG").val(),
            quantidadeEG: $("#quantEG").val(),
            quantidadeXG: $("#quantXG").val(),
            preco: $("#precoprod").val(), 
            precoTotal: $("#precototal").val(),
            observacao: $("#observacaoref").val()
        },
        success : function(data) {                  
           
            
            $("#itens")
            .append("<tr id=\"line" + data +"\">"+
                "<td>" + $("#referencia").val()  + "</td>" +                                        
                "<td>" + $("#quant2").val()  + "</td>" +
                "<td>" + $("#quant4").val()  + "</td>" +
                "<td>" + $("#quant8").val()  + "</td>" +
                "<td>" + $("#quant10").val()  + "</td>" +
                "<td>" + $("#quant12").val()  + "</td>" +
                "<td>" + $("#quant14").val()  + "</td>" +
                "<td>" + $("#quant16").val()  + "</td>" +
                "<td>" + $("#quant18").val()  + "</td>" +
                "<td>" + $("#quantP").val()  + "</td>" +
                "<td>" + $("#quantM").val()  + "</td>" +
                "<td>" + $("#quantG").val()  + "</td>" +
                "<td>" + $("#quantGG").val()  + "</td>" +
                "<td>" + $("#quantEG").val()  + "</td>" +
                "<td>" + $("#quantXG").val()  + "</td>" +
                "<td>" + data.somaQuantidade  + "</td>" +
                "<td>" + $("#precoprod").val()  + "</td>" +
                "<td>" + $("#precototal").val()  + "</td>" +
                "<td>" + $("#observacaoref").val()  + "</td>" +
                "<td><a href=\"javascript:excluiItem('"+data+ "')\">Excluir</a></td>" +
                "</tr>");
            $(".quant,#pid,#referencia,#precoprod,#precototal,#observacaoref").val("");
                    $.ajax({
                            url : 'totalPedido',
                            data : {                              
                            },
                            success: function(data)
                            {
                                $("#displayValorTotal").text((data.toFixed(2)+"").replace(/\./,",  "));
                            }
                    });
                     $.ajax({
                            url : 'totalQuant',
                            data : {                              
                            },
                            success: function(data)
                            {
                                $("#displayQuantTotal").text((data+"").replace(/\./,",  "));
                            }
                    });
        },      
        error : function () 
        {
          alert("Nao foi possível adicionar o Item! Por favor verifique a referencia!");  
        }
    });                
}

function buscarCliente()
{
   
    $.ajax({
        url : 'buscaCliente',
        data : {
            cnpj : $("#cnpj").val()
        },
        success : function(data) {                                             
                  
            $("#selectCliente").val(data);
        }     
                                     
    }); 
                             
}

var keysPressed = [];

function selectAsYouType(e)
{
    var keyChar;var keyNum;
    var comboBox;
    if (window.event) // Internet Explorer
    {
        keyNum = e.keyCode;            
    }
    else
    {
        return true; // browser doesn't support DOM, do default processing.
    }
    
    keyChar = String.fromCharCode(keyNum);
    comboBox = e.srcElement;
    
    if (!comboBox)
    {
        return true; // if DOM didn't work, do default processing
    }
    if (keyNum == 27) // Esc key
    {
        clearKeysPressed(comboBox);
    }
    else
    {
        return selectElement(comboBox, keyChar);
    }
    return true;
}

function clearKeysPressed(e)
{
    if (e.srcElement)
        keysPressed[e.srcElement]="";
}

function selectElement(comboBox, keyChar)
{
    var i = 0;
    var keysPressedSoFar =     keysPressed[comboBox] || "";
    keysPressedSoFar += keyChar;
    keysPressed[comboBox] = keysPressedSoFar;
    var options = comboBox.options;
    for (i = 0; i<options.length; ++i)
    {
        if (options[i].text.toUpperCase().indexOf
                                          (keysPressedSoFar.toUpperCase(), 0) == 0)
        {
            comboBox.selectedIndex = i;
            return false; // don't do default processing
        }
    }
    // didn't match start of any option, so reset keysPressed to just this key
    keysPressed[comboBox] = String(keyChar); 
    return true;        
}
                         
